<template>
  <!-- 新增见证事项 -->
  <el-dialog
    :title="textMap[matterType]"
    draggable
    :modal="matterType !== 'add'"
    :penetrate="true"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="700px"
    @close="cancelFn"
    class="position-left"
  >
    <div class="ui-mt20 ui-mr10">
      <el-form
        ref="dataForm"
        grid
        :rules="rules"
        :model="formData"
        label-width="90px"
        :inline="false"
        size="normal"
      >
        <el-form-item :span="24" label="见证场景" required>
          <el-input v-model="task.taskname" disabled />
        </el-form-item>
        <el-form-item :span="12" label="见证事项" prop="sxid">
          <el-select v-model="formData.sxid" placeholder="请选择见证事项" @change="sxChange">
            <el-option :label="item.sxname" :value="item.id" v-for="item in jzsx" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :span="12" label="状态" prop="itemstate">
          <i style="color: #e82f2f; position: relative; right: 48px">*</i>
          <el-radio-group v-model="formData.itemstate">
            <el-radio label="1">正常</el-radio>
            <el-radio label="0">异常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :span="12" label="事项说明" prop="sxmxid">
          <el-select v-model="formData.sxmxid" placeholder="请选择见证事项">
            <el-option :label="item.name" :value="item.id" v-for="item in sxmxList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发生时间" prop="jltime" :span="12">
          <el-date-picker
            v-model="formData.jltime"
            style="width: 100%"
            unlink-panels
            type="datetime"
            :clearable="true"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
          />
        </el-form-item>
<!--        <el-form-item label="附件信息" :span="24">
          <el-upload
            :key="'fireUploadDialog_'"
            :ref="'fireUploadDialog_'"
            class="fire-upload-dialog"
            action=""
            :limit="10"
            :on-exceed="handleExceed"
            :before-remove="beforeRemoveFn"
            :before-upload="beforeUploadImage"
            :on-remove="onRemoveFn"
            accept=".pdf,.jpg,.png,.jpeg,.gif"
            :http-request="uploadFileFn"
            :on-success="onUploadSuccessFn"
            :on-error="onUploadFailedFn"
          >
            <el-button size="small" icon="el-icon-plus" type="primary" style="width: 100%" dashed>
              点击上传
            </el-button>
          </el-upload>
        </el-form-item>-->
        <el-form-item
          label="见证记录"
          :span="24"
          prop="remark"
        >
          <el-input
            v-model="formData.remark"
            type="textarea"
            style="width: 100%"
            :rows="4"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer">
      <el-button v-if="matterType === 'add'" type="primary" :loading="loading" @click="addJzsxSubmit">提交</el-button>
      <el-button v-if="matterType === 'edit'" type="primary" :loading="loading" @click="updJzsxSubmit">提交</el-button>
      <el-button @click="cancelFn()">取消</el-button>
    </span>
  </el-dialog>
</template>
<script>
import {addJzrecord,updJzrecord} from '../../../../../api/weeon/zbtask'
export default {
  name: "Jzsx",
  props: {
    matterType: {
      type: String,
      default: "add"
    },
    task: {
      type: Object,
      default() {
        return {};
      }
    },
    jzsx: {
      type: Array,
      default() {
        return [/*{
          id: '1',
          sxname: '项目备案',
          sxmxList:[
            {
              id: '11',
              name: '项目备案信息',
            }
          ]
        },{
          id: '2',
          sxname: '项目登记',
          sxmxList:[
            {
              id: '22',
              name: '项目登记信息',
            }
          ]
        }*/];
      }
    },
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      hiddenHint: false,
      dialogTitle: "新增见证事项",
      id: "",
      currProjectData: {},
      pickerOptions: {
        disabledDate(time) {
          console.log("time", time);
          return false; // time.getTime() < Date.now();
        }
      },
      sxmxList: [], // 事项明细
      loading: false,
      visible: false,
      formData: {
        sxid: '',
        sxmxid: '',
        itemstate: "1",
        jltime: '',
        remark: '',
      },
      rules: {
        sxid: [{required: true, message: "见证事项不能为空", trigger: "blur"}],
        sxmxid: [{required: true, message: "事项说明不能为空", trigger: "blur"}],
        jltime: [{required: true, message: "发生时间不能为空", trigger: "blur"}],
        remark: [{ required: true, message: '见证记录不能为空', trigger: 'blur' }]
      },
      textMap: { add: '添加见证记录', edit: '编辑见证记录' }
    };
  },
  computed: {
    // visible() {
    //   return this.show;
    // },
  },
  watch: {

  },
  methods: {

    sxChange(val){
      this.$set(this.formData,'sxmxid','')
      this.sxmxList = []
      const item = this.jzsx.filter(item => item.id === val)
      console.log("item:" + JSON.stringify(item));
      if (item.length > 0) {
        this.sxmxList = item[0].sxmxList;
      }
    },

    /**
     * 新增弹窗
     */
    addJzsx() {
      this.visible = true;
      this.formData = {
        taskid: this.task.id,
        itemstate: "1",
        sxid: '',
        sxname: '',
        sxmxid: '',
        sxmxname: '',
        jltime: '',
        remark: '',
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
     * 修改弹窗
     */
    updateJzsx(row,jzsx) {
      debugger
      this.matterType = 'edit'
      this.formData = {
        id: row.id,
        taskid: row.taskid,
        itemstate: row.itemstate,
        sxid: row.sxid,
        sxname: row.sxname,
        sxmxid: row.sxmxid,
        sxmxname: row.sxmxname,
        jltime: row.jltime,
        remark: row.remark,
      }
      this.jzsx = jzsx;
      this.visible = true;
      this.sxmxList = []
      this.$set(this.formData,'sxmxid','')
      const item = this.jzsx.filter(item => item.id === row.sxid)
      if (item.length > 0) {
        this.sxmxList = item[0].sxmxList;
      }
      this.$set(this.formData,'sxmxid',row.sxmxid)
      // this.formData = Object.assign({}, row)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
     * 保存新增
     */
    async addJzsxSubmit() {
      debugger
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.addJzrecord()
        }
      })
    },
    async addJzrecord(){
      // alert(JSON.stringify(this.formData))
      const res = await addJzrecord(this.formData)
      if (res.stat === 1) {
        this.$emit('jzrecordList');
        this.$message({
          type: "success",
          message: "添加成功",
          single: true
        });
        this.visible = false;
      } else {
        this.$message({
          type: "error",
          message: res.msg,
          single: true
        });
      }
    },

    /**
     * 保存修改
     */
    async updJzsxSubmit() {
      debugger
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.updJzrecord()
        }
      })
    },
    async updJzrecord(){
      // alert(JSON.stringify(this.formData))
      const res = await updJzrecord(this.formData)
      if (res.stat === 1) {
        this.$emit('jzrecordList');
        this.$message({
          type: "success",
          message: "修改成功",
          single: true
        });
        this.visible = false;
      } else {
        this.$message({
          type: "error",
          message: res.msg,
          single: true
        });
      }
    },

    //  限制上传图片格式
    beforeUploadImage(file) {
      console.log("file.szie", file.size);
      console.log("file.type", file.type);
      const isSize = file.size / 1024 / 1024; // 文件大小
      const fileSize = 5;
      if (isSize > fileSize) {
        this.uploadFlag = true;
        // this.$message.error(`上传图片大小不能超过${fileSize}MB!`);
        this.$msgbox({
          title: "提示",
          message: `文件大小不能超过${fileSize}MB，请重新上传。`,
          type: "warning"
        });
        return false;
      }
      return true;
    },
    // 文件相关
    beforeRemoveFn(file) {
      if (!this.uploadFlag) {
        return this.$confirm(`确定移除 ${file.name}？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
      }
    },
    onRemoveFn(file) {
      for (const [index, item] of this.addform.attachmentList.entries()) {
        if (item.uid === file.uid) {
          this.addform.attachmentList.splice(index, 1);
          return;
        }
      }
    },
    async uploadFileFn(params) {
      try {
        const form = new FormData();
        form.append("file", params.file);
        const res = await uploadFile(form);
        if (res.success) {
          this.addform.attachmentList.push({
            ...params.file,
            attachId: res.data
          });
        }
      } catch (error) {
        console.error(error);
        this.$message({
          type: "error",
          message: "上传文件失败，请稍后再试",
          single: true
        });
      }
    },
    onUploadSuccessFn() {
      this.$message({
        type: "success",
        message: "上传文件成功!",
        single: true
      });
    },
    handleExceed() {
      // files, fileList
      this.$message.warning(`当前限制最多上传 10 个文件`);
    },
    onUploadFailedFn() {
      this.$message({
        type: "error",
        message: "上传文件失败，请稍后再试",
        single: true
      });
    },
    handleErrorLevelChangeFn() {
      this.$refs.addform.validateField("status");
    },
    handleClickAddFn() {
      document.getElementsByClassName("el-upload__input")[0].click();
    },
    cancelFn() {
      this.visible = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.witness-matter-warning {
  position: absolute;
  height: 14px;
  overflow: hidden;
  width: 120%;
  left: 0;
  top: 34px;
  color: $orange;
  line-height: 14px;
  font-size: 12px;
  z-index: 9;
  background: #fff;
}

.fire-upload-dialog {
  width: 100%;

  ::v-deep .el-upload {
    width: 100%;
  }
}

.position-left {
  ::v-deep .el-dialog__body {
    max-height: 465px !important;
  }
}

.daishenhe-tag {
  position: absolute;
  top: 60px;
  right: 15px;

  i {
    font-size: 70px;
    color: $primary;
  }
}

.ui-table th,
.ui-table td {
  width: 275px;
}

.position-left {
  position: absolute;
}

.position-left {
  ::v-deep .el-dialog__body {
    max-height: 465px !important;
  }
}

.warn-tip {
  position: absolute;
  bottom: 14px;

  i {
    color: #fc9306;
    font-size: 18px;
  }

  span {
    font-size: 16px;
    color: #333333;
    padding-left: 5px;
  }
}

.verification-warn-tip {
  font-size: 12px;
  width: 365px;
  font-family: MicrosoftYaHei;
  color: #fc9306;
  line-height: 19px;
  margin-bottom: -15px;
}
</style>

<style lang="scss">

.el-popper {
  .el-cascader-node {
    height: auto;
    min-height: 34px;

    .el-cascader-node__label {
      word-break: break-all;
      white-space: normal;
      flex: 1;
      padding: 0 10px;
      margin: 4px auto;
      line-height: 15px;
    }
  }
}
</style>
